// @ts-ignore
const initSqlJs = require('sql.js')

let db: any = null

export async function initializeDatabase(): Promise<any> {
  if (db) {
    return db
  }

  const SQL = await initSqlJs()
  db = new SQL.Database()

  // 创建用户表
  db.run(`
    CREATE TABLE IF NOT EXISTS users (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT NOT NULL,
      email TEXT UNIQUE NOT NULL,
      age INTEGER NOT NULL,
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )
  `)

  // 插入示例数据
  const countResult = db.exec('SELECT COUNT(*) as count FROM users')
  const userCount = countResult.length > 0 && countResult[0] && countResult[0].values.length > 0 && countResult[0].values[0]
    ? countResult[0].values[0][0] 
    : 0
  if (userCount === 0) {
    db.run(`
      INSERT INTO users (name, email, age) VALUES 
      ('张三', 'zhangsan@example.com', 25),
      ('李四', 'lisi@example.com', 30),
      ('王五', 'wangwu@example.com', 28)
    `)
  }

  console.log('Database initialized successfully')
  return db
}

export function getDatabase(): any {
  if (!db) {
    throw new Error('Database not initialized. Call initializeDatabase first.')
  }
  return db
}
